package com.ytjj.common.utils;

import org.apache.commons.lang3.time.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class DateTimeUtil {
    /**
     * 获取当前的日期yyyy-MM-dd
     */
    public static String getDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }


    public static String getDate2() {
        return new SimpleDateFormat("yyyy-MM-01").format(new Date());
    }

    public static String getDate(String formater) {
        return new SimpleDateFormat(formater).format(new Date());
    }

    /**
     * 获取当前的时间yyyy-MM-dd HH:mm:ss
     */
    public static String getTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 获取当前的年份yyyy
     */
    public static int getYear() {
        Calendar a = Calendar.getInstance();
        return a.get(Calendar.YEAR);
    }

    /**
     * 字符串转日期
     *
     * @param str
     * @return
     */
    public static Date StrToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Date StrToDate(String str,String pattern) {

        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 字符串转时间
     *
     * @param str,formats
     * @return
     */
    public static Date StrToTime(String str, String formats) {

        SimpleDateFormat format = new SimpleDateFormat(formats);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 字符串转时间
     *
     * @param str
     * @return
     */
    public static Date StrToTime(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 入参时间是否超间隔时间（小时）
     * @param startDate 开始时间
     * @param interval 小时
     * @return boolean true:已超时 false:未超时
     */
    public static boolean isTimeOut(Date startDate,long interval){
        boolean result = true;
        if (startDate != null) {
            long value = System.currentTimeMillis() - startDate.getTime();
            long valueHour = value / 1000 / 3600;
            //时间不超过 interval 小时，不记录异常
            if (valueHour < interval) {
                result = false;
            }
        }
        return result;
    }

    /**
     * 日期转字符串
     *
     * @param str
     * @return
     */
    public static String DateToStr(Date date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        return str;
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 时间转字符串
     *
     * @param str
     * @return
     */
    public static String TimeToStr(Date time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(time);
        return str;
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    public static Integer dateToTimestamp() {
        return (int) (System.currentTimeMillis() / 1000);
    }


    /**
     * 获取当前的日期加xxx天后yyyy-MM-dd
     *
     * public static String getDate(int x) { org.joda.time.DateTime dt =
     * org.joda.time.DateTime.now(); org.joda.time.DateTime dt2 = dt.plusDays(x);
     * return dt2.toString("yyyy-MM-dd"); }
     */
    /**
     * 比较日期大小
     *
     * @param date
     * @param date1
     * @return
     */
    public static boolean compare(String date1) {
        Date date = new Date();
        Date d = StrToTime(getDate() + " " + date1 + ":00");
        return d.before(date);
    }

    public static boolean compareTime(String spaceTime, String endTime) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String str = format.format(date);
        int hours = Integer.valueOf(str.split(":")[0]);
        int mins = Integer.valueOf(str.split(":")[1]) + Integer.valueOf(spaceTime);
        if (mins / 60 > 0) {
            hours = hours + mins / 60;
            mins = mins % 60;
        }
        Calendar now = Calendar.getInstance();
        now.set(hours, mins);
        return now.before(getDate() + " " + endTime + ":00");
    }

    public static Boolean compareTime2(String date1,String date2) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Boolean result = false ;
        try{
            Date time1 = format.parse(date1);
            Date time2 = format.parse(date2);
            return time1.before(time2);
        }  catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean TimeDifference(String alertTime, int spaceTime) {
        boolean isSend = false;
        Date d = StrToTime(getDate() + " " + alertTime + ":00");

        Calendar now = Calendar.getInstance();

        int i = (int) (now.getTimeInMillis() - d.getTime()) / 1000 / 60;

        if (i / spaceTime >= 0 || i % spaceTime < 1) {
            isSend = true;
        }
        return isSend;
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 时间戳转当前时间 10位数
     *
     * @param s
     * @return
     */
    public static String stampToTimeOne(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s) * 1000;
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 时间戳转当前时间 13位数
     *
     * @param s
     * @return
     */
    public static String stampToTimeTwo(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 获取当前时间11位时间戳
     *
     * @return
     */
    public static Integer dateToTimestamp(Date date) {
        return (int) (date.getTime() / 1000);
    }

    public static int hoursBetween2(String startTime, String endTime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        return hoursBetween2(sdf.parse(startTime), sdf.parse(endTime));
    }

    public static int hoursBetween2(Date startTime, Date endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        Calendar cal = Calendar.getInstance();
        long time1 = 0;
        long time2 = 0;

        try {
            cal.setTime(startTime);
            time1 = cal.getTimeInMillis();
            cal.setTime(endTime);
            time2 = cal.getTimeInMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long between_hours = (time2 - time1) / (1000 * 3600);

        return Integer.parseInt(String.valueOf(between_hours));
    }

    public static String getDateWithWeekDay(LocalDateTime date) {
        int iWeekDay = date.getDayOfWeek().getValue();

        String today = date.getYear() + "年" + date.getMonthValue() + "月" + date.getDayOfMonth() + "日";
        String weekDay = "";

        if (iWeekDay == 1) {
            weekDay = "星期一";
        } else if (iWeekDay == 2) {
            weekDay = "星期二";
        } else if (iWeekDay == 3) {
            weekDay = "星期三";
        } else if (iWeekDay == 4) {
            weekDay = "星期四";
        } else if (iWeekDay == 5) {
            weekDay = "星期五";
        } else if (iWeekDay == 6) {
            weekDay = "星期六";
        } else if (iWeekDay == 7) {
            weekDay = "星期日";
        }

        return today + " " + weekDay;
    }

    public static int getAge(String date) {
        LocalDate today = LocalDate.now();
        LocalDate playerDate = LocalDate.from(DateTimeFormatter.ofPattern("yyyy-MM-dd").parse(date));
        long years = ChronoUnit.YEARS.between(playerDate, today);
        return (int) years;
    }

    /**
     * 指定时间基础上加 addnumber 分钟数
     * @param timeStr 基础时间
     * @param addnumber 需要累加的分钟数
     * @return String
     */
    public static String addtime(String timeStr, Integer addnumber) {
        String str = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date date = df.parse(timeStr);
            //时间累计
            Calendar gc = new GregorianCalendar();
            gc.setTime(date);
            gc.add(GregorianCalendar.MINUTE, addnumber);
            str = df.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 指定时间基础上加天数
     * @param timeStr 基础时间字符串yyyy-MM-dd
     * @param day 需要累加的天数
     * @return String
     */
    public static String addDay(String timeStr, Integer day) {
        String str = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date date = df.parse(timeStr);
            //时间累计
            Calendar gc = new GregorianCalendar();
            gc.setTime(date);
            gc.add(Calendar.DAY_OF_MONTH, day);
            str = df.format(gc.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 获取当前系统时间戳（11位）
     *
     * @return
     */
    public static Integer currentTimestamp() {
        return Integer.valueOf((System.currentTimeMillis() / 1000) + "");
    }

    /**
     * 根据时间排序
     *
     * @param list
     */
    public static void listSort(List<String> list, String formatStr) {
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                SimpleDateFormat format = new SimpleDateFormat(formatStr);
                try {
                    Date dt1 = format.parse(o1);
                    Date dt2 = format.parse(o2);
                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    /**
     * 获取当年的第一天
     *
     * @param year
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     *
     * @param year
     * @return
     */
    public static Date getCurrYearLast() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }

    /**
     * 获取本月开始日期
     *
     * @return String
     **/
    public static String getMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 00：00：00";
    }

    /**
     * 获取本月最后一天
     *
     * @return String
     **/
    public static String getMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 23:59:59";
    }

    /**
     * 获取本周的第一天
     *
     * @return String
     **/
    public static String getWeekStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 00:00:00";
    }

    /**
     * 获取本周的最后一天
     *
     * @return String
     **/
    public static String getWeekEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 23:59:59";
    }

    /**
     * 获取本年的第一天
     *
     * @return String
     **/
    public static String getYearStart() {
        return new SimpleDateFormat("yyyy").format(new Date()) + "-01-01";
    }

    /**
     * 获取本年的最后一天
     *
     * @return String
     **/
    public static String getYearEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date currYearLast = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast) + " 23:59:59";
    }

    public static String dayAddNum(Date time, Integer num){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.DAY_OF_MONTH, num);
        Date newTime = calendar.getTime();
        return DateToStr(newTime);
    }

    /**

     * 日期格式转换yyyy-MM-dd'T'HH:mm:ss.SSSXXX (yyyy-MM-dd'T'HH:mm:ss.SSSZ) TO yyyy-MM-dd HH:mm:ss

     * 2020-04-09T23:00:00.000+08:00 TO 2020-04-09 23:00:00

     * @throws ParseException

     */

    public static String dealDateFormat(String oldDateStr) {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
            Date date = df.parse(oldDateStr);
            SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            Date date1 = df1.parse(date.toString());
            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df2.format(date1);
        } catch (ParseException e) {
            Date payTime = DateTimeUtil.StrToTime(oldDateStr,"yyyyMMddHHmmss");
            return DateTimeUtil.TimeToStr(payTime);
        }
    }

    /**
     * 处理字符串格式2024-06-29T19:29:37+08:00 为Date类型
     */
    public static Date dealIsoDateToDate(String isoDateTimeString) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        OffsetDateTime odt = OffsetDateTime.parse(isoDateTimeString, formatter);
        // 将OffsetDateTime转换为Instant，再从Instant转换为Date
        Date date = Date.from(odt.toInstant());
        return date;
    }

    public static void main(String[] args) {
        try {
//            Date date = DateTimeUtil.dealIsoDateToDate("2024-06-29T19:29:37+08:00");

            System.out.println(compareTime2("2024-02-14 11:32:47","2024-01-23 14:52:43"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某一天的最后一毫秒的日期值
     */
    public static Date getEndOfDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    /**
     * 获取指定日期的0点0分的时间
     */
    public static Date getBeginOfDay(Date date) {
        return DateUtils.truncate(date, Calendar.DATE);
    }

    /**
     * 计算两个日期见相差多少天
     */
    public static int daysBetweenDiff(Date startDate, Date endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            startDate = sdf.parse(sdf.format(startDate));
            endDate = sdf.parse(sdf.format(endDate));
        } catch (ParseException e) {
            e.getMessage();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(startDate);
        long time1 = cal.getTimeInMillis();

        cal.setTime(endDate);
        long time2 = cal.getTimeInMillis();

        long betweenDays = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(betweenDays));
    }

    public static int getLastSeconds() {
        Date date = new Date();
        //使用plusDays加传入的时间加1天，将时分秒设置成0
        LocalDateTime midnight = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        //使用ChronoUnit.SECONDS.between方法，传入两个LocalDateTime对象即可得到相差的秒数
        Long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return seconds.intValue();
    }

}
